package com.common;

import cn.hutool.core.io.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * ClassName:AppFileUtils
 */
@Component
@PropertySource("classpath:file.properties")
public class AppFileUtils {
    /**
     * @Value注解对这个属性进行赋值，结果注不进去。
     * 解决方案：
     *      1.将这两个私有属性的set方法从私有变成公开(private -->>> public);
     *      2.生成这两个静态属性的set方法；
     *      3.将原来在静态属性上的@Value() 注解改到设在 set方法上；
     *      4.去除这两个静态属性set方法的static关键字
     *      类上面的@Component 注解一定要有。
     */
    //文件上传的保存路径
    public static String UPLOAD_PATH;//默认值
    // 文件保存目录
    public static String DIR_PATH;

    @Value("${filepath}")
    public void setUploadPath(String uploadPath) {
        UPLOAD_PATH = uploadPath;
    }

    @Value("${dirpath}")
    public void setDirPath(String dirPath) {
        DIR_PATH = dirPath;
    }

    /**
     * 文件下载
     * @param path
     * @return
     */
    public static ResponseEntity<byte[]> downloadFile(HttpServletResponse response, String path, String oldName) {
        //1,构造文件对象
        File file = new File(UPLOAD_PATH,path.replace(DIR_PATH,""));
        if (file.exists()) {
            try {
                //将下载的文件，封装byte[]
                byte[] bytes = null;
                try {
                    bytes = FileUtil.readBytes(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //创建封装响应头信息的对象
                HttpHeaders header = new HttpHeaders();
                //封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
                header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                //设置下载的文件的名称
                //header.setContentDispositionFormData("attachment", oldName);
                //创建ResponseEntity对象
                return new ResponseEntity<>(bytes, header, HttpStatus.CREATED);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            PrintWriter out;
            try {
                out = response.getWriter();
                out.write("文件不存在");
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 根据相对路径删除硬盘上文件
     *
     * @param path
     */
    public static void deleteFileUsePath(String path) {
        String realPath = UPLOAD_PATH + path;
        //根据文件
        File file = new File(realPath);
        if (file.exists()) {
            file.delete();
            System.out.println("文件删除成功！");
        }
    }

    /**
     * 删除文件临时后缀
     *
     * @param imgPath 带后缀的原文件全名
     * @param suffix  要删除的文件后缀名
     * @return 修改后名称
     */
    public static String updateFileName(String imgPath, String suffix) {
        //找到文件
        try {
            File file = new File(UPLOAD_PATH, imgPath);
            if (file.exists() && file.renameTo(new File(UPLOAD_PATH, imgPath.replace(suffix, "")))) {
                return imgPath.replace(suffix, "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据路径 删除图片
     *
     * @param imgName
     */
    public static void removeFileByPath(String imgName) {
        try {
            File file = new File(UPLOAD_PATH, imgName);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
